<?php

defined('_JEXEC') or die();

jimport('joomla.application.component.controller');

require_once(JPATH_COMPONENT.DS.'helpers'.DS.'extensionsHelper.php');

class Easiv2ControllerManageExtensions extends JController {
	
	var $db;
	var $extensionsHelper;
	
	function __construct() {
		parent::__construct();
		
		$this->db =& JFactory::getDBO();
		$this->extensionsHelper = new ExtensionsHelper('repository');
	}
	
	function display() {
		
		parent::display();
	}
	
	function getInfo() {
		//$params = xmlrpc_decode($_POST['params']);
		$v = new JVersion();
		$version = $v->getShortVersion();
		
		echo $version;
	}
	
	function isExtensionInstalled() {		
		$param = xmlrpc_decode($_POST['extension']);
		
		$this->db->setQuery('SELECT name, manifest_cache FROM #__extensions WHERE name = "'.$param.'"');
		$result = $this->db->loadObject();
		
		if(count($result) != 0) {
			// to get to the version info the content of the manifest_cache attribute of the #__extensions table is read.
			$mc = $result->manifest_cache;
		
			/*
			 * the first appearance of the word version is discovered. The result looks like this:
			 * 
			 * version":"1.5.0","description":"It counts the shopping entries","group":""}
			 * 
			 * Next, the position of the ':'-seperator charakter is discovered
			 * 
			 * The result looks like this:
			 */
			$temp = stristr($mc, 'version');
			$seperatorPos = strpos($temp, ':');
			
			/*
			 * Next, the string from the startposition of $temp to the found seperator position is stored in $temp again
			 * 
			 * $temp would now look like this:
			 * 
			 * :"1.5.0","description":"It counts the shopping entries","group":""}
			 */
			$temp = substr($temp, $seperatorPos);
			
			/*
			 * Next, the ','-seperator position is dicovered
			 */
			$seperatorPos = strpos($temp, ',');
			
			/*
			 * Now the version can be read with the following command
			 */
			$version = substr($temp, 2, $seperatorPos-3);
			
			// the answer will be true for installstatus followed by a ':'-seperator and the version number
			echo "true:".$version;
		}
		else {
			echo "false";
		}
	}
	
	function install() {
		$param = xmlrpc_decode($_POST['toInstall']);
		
		if($this->extensionsHelper->install(JPATH_COMPONENT.DS.'repository'.DS.$param)) {
			echo "true";
		}
		else {
			echo "false";
		}
	}
	
	function uninstall() {
		$param = xmlrpc_decode($_POST['information']);
		
		$extensionName = $param[0];
		$type = $param[1];
		
		$this->db->setQuery("SELECT extension_id FROM #__extensions WHERE name ='".$extensionName."'");
		
		$extensionId = $this->db->loadObject()->extension_id;
		
		$installer = new JInstaller();
		
		if(@$installer->uninstall($type, $extensionId, 0)) {
			echo "true";
		}
		else {
			echo "false";
		}
	}
}